package cn.gson.crm.controller.permission;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;
import javax.validation.Valid;

import org.hibernate.Hibernate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.gson.crm.model.dao.PictureTestDao;
import cn.gson.crm.model.entity.BrandModel;
import cn.gson.crm.model.entity.Picture;

@Controller
@RequestMapping("photo")
public class PhotoTestController {
	
	@Autowired
	PictureTestDao pDao;

	@GetMapping
	public String indexTest() {
		return "permission/photo";
	}
	
	@PostMapping("save")
	@ResponseBody
	@Transactional
	public boolean save(@Valid BrandModel brandModel, BindingResult br) {
		if(br.hasErrors()) {
			System.out.println(br.getAllErrors().toString());
			return false;
		} else {
			try {
//				Picture picture = new Picture();
//				picture.setData(brandModel.getSourceFile().getBytes());
//				pDao.save(picture);
				ByteArrayInputStream byIntStream = new ByteArrayInputStream(brandModel.getSourceFile().getBytes());
				BufferedImage bufImg = ImageIO.read(byIntStream);
				SimpleDateFormat f=new SimpleDateFormat("yyyyMMddhhmmss");
				String fileName = f.format(new Date());
//				File file = new File("src/main/webapp/images/employee_photo/" + fileName + ".jpg");
				File file = new File("C:/Users/madodo/Desktop/javapictest/" + fileName + ".jpg");
				if (!file.exists()) {
	                file.mkdirs();
	            } 
				ImageIO.write(bufImg, "jpg", file);
//				Picture picture = new Picture();
//				picture.setData(sourceFile.getBytes());
//				pDao.save(picture);
//				return true;
				return true;
			} catch (Exception e) {
				return false;
			}
		}
	}
	
	
}
